package com.gxa.p2p.interceptor;

import com.gxa.p2p.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@CrossOrigin
public class JWTInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
      throws Exception {
    // 需要工具类JWTUtil来解析前端的请求头: Authorization
    JWTUtil util = new JWTUtil();
    String jwt = request.getHeader("Authorization");
    try {
      if (jwt == null) {
        System.out.println("请求头为空, 验证失败");
      } else {
        Claims c = util.parseJWT(jwt);

        // 通过Claim对象,可以获取在jwt中保存的特征(Map)
        System.out.println("id为" + c.get("id") + "的用户已是登录状态");
        // 返回true表示放行
        return true;
      }
      System.out.println("token解析错误，验证失败");
    } catch (Exception e) {
      e.printStackTrace();
    }
    // 当返回false的时候, 表示被拦截住,没法访问controller
    return false;
  }

  @Override
  public void postHandle(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Object o,
      ModelAndView modelAndView)
      throws Exception {}

  @Override
  public void afterCompletion(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Object o,
      Exception e)
      throws Exception {}
}
